package com.ruoyi.comment.service.impl;

import cn.hutool.core.bean.BeanUtil;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.ruoyi.comment.mapper.QuestionsMapper;

import com.ruoyi.comment.service.IQuestionsService;

import com.ruoyi.common.core.redis.RedisCache;

import com.ruoyi.model.auth.AuthContextHolder;

import com.ruoyi.model.question.Question;
import com.ruoyi.model.question.dto.QuestionDTO;
import com.ruoyi.model.question.vo.QuestionVO;
import com.ruoyi.model.user.UserInfo;
import lombok.extern.slf4j.Slf4j;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.*;


/**
 * @author : Afanda
 **/
@Service
@Slf4j
public class QuestionsServiceImpl extends ServiceImpl<QuestionsMapper, Question> implements IQuestionsService {

    /**
     * redis缓存服务
     */
    @Resource
    private RedisCache redisCache;


    @Resource
    private QuestionsMapper questionsMapper;


    /**
     * 发布提问
     *
     * @param questionDTO 发布提问的内容
     * @return 发布是否成功
     */
    @Override
    @Transactional
    public boolean sendCommentContent(QuestionDTO questionDTO) {
        UserInfo userInfo = AuthContextHolder.getUserInfo();

        if (questionDTO != null && questionDTO.getUserId() != null && userInfo != null) {
            Question question = BeanUtil.copyProperties(questionDTO, Question.class);
            question.setUserId(userInfo.getId());
            question.setUserName(userInfo.getName());
            question.setUserPhoto(userInfo.getAvatar());
            question.setSchool(userInfo.getSchool());
            question.setCreateTime(LocalDateTime.now());
            question.setPushTime(LocalDateTime.now());
            question.setUpdateTime(LocalDateTime.now());


            this.save(question);
            return true;
        }
        throw new RuntimeException("数据可能发生异常");
    }


    /*
     * 根据id查询提问
     * */
    @Override
    public QuestionVO queryById(String id) {
        Question question = questionsMapper.queryById(id);
        if (question == null) {
            throw new RuntimeException("未查询到该用户");
        }
        // 用户提问组合token
        String currentUserQuestion = new StringBuffer()
                .append(AuthContextHolder.getUserId())
                .append("_")
                .append(question.getId()).toString();
        // 得到用户上一次访问的时间
        Long startTimes = redisCache.getCacheObject(currentUserQuestion);
        // 如果用户第一次访问或者对于上一次的访问时间大于5分钟就计入阅读量
        if (startTimes == null || System.currentTimeMillis() - startTimes > 5 * 60 * 1000) {
            // todo 阅读量+1
            questionsMapper.increaseReading(question.getId());
            // 存储用户上一次访问提问的时间(毫秒)
            redisCache.setCacheObject(currentUserQuestion, System.currentTimeMillis());
        }
        return BeanUtil.copyProperties(question, QuestionVO.class);
    }

    /*
     * 根据id删除提问
     * */
    @Override
    public void removeByIdQuestions(String id) {
        Question byId = this.getById(id);
        if (byId != null && byId.getIsDel() == 0) {
            questionsMapper.removeByIdQuestions(id);
        } else {
            throw new RuntimeException("删除失败");
        }
    }

    /*
     * 批量查询
     * */
    @Override
    public List<QuestionVO> queryList(Integer page, Integer pageSize) {
        PageHelper.startPage(page, pageSize);
        List<QuestionVO> questionVOList = questionsMapper.queryList();
        String[] searchTag = {"<p>", "<span>"};
        int startIndex = -1, endIndex = -1;
        for (QuestionVO questionVO : questionVOList) {
            String content = questionVO.getContent();
            questionVO.setContent("该问题需要进入详情查看");

            // 从用户提问内容中截取展示部分
            for (String tag : searchTag) {
                startIndex = content.indexOf(tag);
                if (startIndex != -1) {
                    endIndex = content.indexOf(new StringBuffer(tag).insert(1, '/').toString());
                    break;
                }
            } 

            // 截取成功
            if (startIndex != -1) {
                // 截取用户展示内容
                String showContent = content.substring(startIndex + 3, endIndex);
                // 防止用户展示内容过多
                if (showContent.length() > 200) {
                    showContent = showContent.substring(0, 200);
                }
                questionVO.setContent(showContent);
            }
        }

        return questionVOList;
    }
}
